package com.example.suanfademo;

import java.security.KeyStore;

public class LinkedList {
    private int size;
    private ListNode head;

    public LinkedList(){
        this.size=0;
        this.head=new ListNode(0);
    }

    public int getIndex(int index){
        if(index<0 || index>size){
            return -1;
        }
        ListNode current=head;
        for(int i=0;i<index;i++){
            current=current.next;
        }
        return current.val;
    }

    public void add(int val){
        ListNode listNode = new ListNode(val);
        if(head == null){
            head = listNode;
        }
        ListNode current =head;
        while (current.next !=null){
            current=current.next;
        }
        current.next=listNode;
        size++;
    }
    public void addAtHead(int val){
        ListNode listNode = new ListNode(val);

        listNode.next=head.next;
        head.next =listNode;
        size++;
    }

    public void addAtTail(int val){
        ListNode listNode = new ListNode(val);
        ListNode cur=head;
        while (cur.next!=null){
            cur=cur.next;
        }
        cur.next=listNode;
        size++;
    }

    public void addAtIndex(int index,int val){
        ListNode listNode = new ListNode(val);
        ListNode pre=head;
        for(int i=0;i<index-1;i++){
            pre=pre.next;
        }
        listNode.next=pre.next;
        pre.next=listNode;
        size++;
    }

    public void deleteAtIndex(int index){
        ListNode pre =head;
        for(int i=0;i<index-1;i++){
            pre=pre.next;
        }
        pre.next= pre.next.next;
        size--;
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
//        int index = list.getIndex(2);
//        System.out.println(index);
//        list.addAtHead(88);
//        int index1 = list.getIndex(1);
//        System.out.println(index1);
//        list.addAtTail(100);
//        int index2 = list.getIndex(5);
//        System.out.println(index2);
        // 在index位置 添加元素
        list.addAtIndex(2,77);
        int index = list.getIndex(2);
        System.out.println(index);
        list.deleteAtIndex(2);
        System.out.println(list.getIndex(2));
    }

}
